package cn.easybuy.service.order;

import java.util.List;

import cn.easybuy.dao.Order_detailDao;
import cn.easybuy.dao.ProductDao;
import cn.easybuy.dao.impl.Order_detailDaoImpl;
import cn.easybuy.dao.impl.ProductDaoImpl;
import cn.easybuy.entity.OrderAndProduct;
import cn.easybuy.entity.Order_detail;
import cn.easybuy.utils.DataSourceUtil;
import cn.easybuy.utils.ShoppingCartItem;

public class Order_DetailServiceImpl implements Order_DetailService {
	ProductDao pdao = new ProductDaoImpl(DataSourceUtil.getConnection());

	@Override
	public int addOrderDetail(int OrderId,List<ShoppingCartItem> list) {
		// TODO Auto-generated method stub
		Order_detailDao odao = new Order_detailDaoImpl(DataSourceUtil.getConnection());
		try {
			for (ShoppingCartItem sc : list) {
				Order_detail od=new Order_detail();
				od.setOrderId(OrderId);
				od.setProductId(sc.getProduct().getId());
				od.setQuantity(sc.getQuantity());
				od.setCost(sc.getCost());
				int k=odao.addOrderDetail(od);
				if(k>0){
					System.out.println("商品订单详情添加成功");
					//减少商品库存
					if(pdao.subtractStock(od.getProductId()+"",od.getQuantity())>0){
						System.out.println("商品库存已经更新！");
					}
				}else{
					System.out.println("商品订单详情添加失败");
					throw new Exception();
				}
			}
		} catch (Exception e) {
			return 0;
		}
		return 1;
	}

	@Override
	public List<OrderAndProduct> FindOrder_DetailToId(String id) {
		Order_detailDao odao = new Order_detailDaoImpl(DataSourceUtil.getConnection());
		return odao.FindOrder_DetailToId(id);
	}

}
